﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using MediaClient.Common;
using MediaDataModel.Common.Other;
using MediaDataModel;
using System.IO;
using System.Threading;

namespace MediaClient.Publish
{
    public partial class PublishSettingForm : BaseSmallForm
    {
        List<KeyValue> waterMarkerList = new List<KeyValue>();
        List<KeyValue> publishList = new List<KeyValue>();
        private short publishFlag = 1;
        private long mediaPackID = 0;
        private string discBarcode = "";

        public PublishSettingForm()
        {
            InitializeComponent();
        }

        public PublishSettingForm(long mediaPackID,short publishFlag)
            : this()
        {
            this.publishFlag = publishFlag;
            this.mediaPackID = mediaPackID;
        }

        private void PublishSettingForm_Load(object sender, EventArgs e)
        {
            ComboBoxBindData();
            switch (publishFlag)
            {
                case 2:
                    lblSavePath.Visible = txtSavePath.Visible = btnBrowse.Visible = true;
                    lblLogo.Image = global::MediaClient.Properties.Resources.文件_发行;
                    break;
                case 3:
                    lblDesDrive.Visible = cmbDesDrive.Visible = true;
                    lblDesDrive.Location = lblSavePath.Location;
                    cmbDesDrive.Location = txtSavePath.Location;
                    lblLogo.Image = global::MediaClient.Properties.Resources.光盘_发行;
                    break;
                case 1:
                default:
                    break;
            }

            LoadDiscDrive();
            if (cmbCompany.Items.Count == 0)
            {
                MessageBox.Show("系统暂时没有客户，请到 “系统设置”管理模块添加客户信息后，再进行发行", BaseForm.MessageBoxCaption);
                btnBurning.Visible = false;
            }
        }

        private void ComboBoxBindData()
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(BaseForm.systemConfigFile);

                //水印频率
                XmlNodeList waterMaikerNodeList = xmlDoc.DocumentElement.SelectNodes("waterMarker/marker");
                foreach (XmlNode waterMarkerNode in waterMaikerNodeList)
                    cboWaterMarker.Items.Add(new KeyValue { Key = waterMarkerNode.Attributes["name"].Value, Value = waterMarkerNode.Attributes["value"].Value });
                cboWaterMarker.SelectedIndex = 0;

                //视频码率
                XmlNodeList videoRateNodeList = xmlDoc.DocumentElement.SelectNodes("video/bitRate/publish/rate");
                foreach (XmlNode rateNode in videoRateNodeList)
                    cboVideoBitrate.Items.Add(new KeyValue { Key = rateNode.Attributes["name"].Value, Value = rateNode.Attributes["value"].Value });
                cboVideoBitrate.SelectedIndex = 0;

                //视频格式
                XmlNodeList videoExtensionNodeList = xmlDoc.DocumentElement.SelectNodes("video/extensions/extension");
                foreach (XmlNode childNode in videoExtensionNodeList)
                    cboVideoFormat.Items.Add(childNode.InnerText);
                cboVideoFormat.SelectedIndex = 0;

                //发行公司
                using (CCTV6Entities db = new CCTV6Entities())
                {
                    var customers = db.Customers.Where(customer => customer.IsOwner.HasValue== false || customer.IsOwner.Value == false);
                    if (customers != null && customers.Count() > 0)
                    {
                        foreach (var customer in customers)
                            cmbCompany.Items.Add(customer);
                        
                        cmbCompany.SelectedIndex = 0;
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        private void ReadXml(XmlNode root)
        {
            foreach (XmlElement xe in root.ChildNodes)
            {
                if (xe.ChildNodes.Count != 0)
                {
                    ReadXml(xe);
                }
                else
                {
                    switch (xe.ParentNode.Name)
                    {
                        case "publish":
                            KeyValue kv = new KeyValue();
                            kv.Key = xe.GetAttribute("name");
                            kv.Value = xe.GetAttribute("value");
                            publishList.Add(kv);
                            break;
                        case "waterMarker":
                            KeyValue kv1 = new KeyValue();
                            kv1.Key = xe.GetAttribute("name");
                            kv1.Value = xe.GetAttribute("value");
                            waterMarkerList.Add(kv1);
                            break;
                    }
                }
            }
        }

        private void LoadDiscDrive()
        {
            
            Dictionary<string, DiscState> localDiscDrives = BurnHelper.InitAndGetDriversName();
            if (localDiscDrives.Count == 0)
            {
                MessageBox.Show("本机光驱不可用，没办法读取光盘信息。", BaseForm.MessageBoxCaption);
                btnBurning.Visible = false;
                return;
            }
            else if (this.publishFlag == 3 && localDiscDrives.Count == 1)
            {
                MessageBox.Show("本机只有一个光驱，无法进行 “光盘发行”。", BaseForm.MessageBoxCaption);
                btnBurning.Visible = false;
            }

            foreach (var drive in localDiscDrives)
            {
                cmbSourceDrive.Items.Add(drive.Key);
                cmbDesDrive.Items.Add(drive.Key);
            }
            if (cmbSourceDrive.Items.Count != 0)
                cmbSourceDrive.SelectedIndex = 0;
            if (cmbDesDrive.Items.Count > 1)
                cmbDesDrive.SelectedIndex = 1;
            else if (cmbDesDrive.Items.Count == 1)
                cmbDesDrive.SelectedIndex = 0;
        }

        private List<DiscFile> GetMediaPackFiles()
        {
            List<DiscFile> mediaPackFileList = new List<DiscFile>();
            if (this.mediaPackID != 0)
            {
                using (CCTV6Entities db = new CCTV6Entities())
                {
                    MediaPack oMediaPack = db.MediaPacks.SingleOrDefault(media => media.ID == this.mediaPackID);
                    if (oMediaPack != null && string.IsNullOrEmpty(oMediaPack.DiscBarcode) == false)
                    {
                        this.discBarcode = oMediaPack.DiscBarcode;
                        mediaPackFileList = db.DiscFiles.Where(mediaFile => mediaFile.MediaPackID == this.mediaPackID && mediaFile.DiscBarcode == this.discBarcode).ToList();
                    }
                }
            }
            return mediaPackFileList;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //if (fdPublishFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //    txtSavePath.Text = fdPublishFolder.SelectedPath;
            SaveFileDialog file = new SaveFileDialog();
            file.Filter = "MPEG FILL(*.mpg)|*.mpg";
            if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //targetFile = file.FileName;
                txtSavePath.Text = file.FileName;
            }
        }

        private void btnBurning_Click(object sender, EventArgs e)
        {
            //if (publishFlag == 3 && cmbDesDrive.SelectedItem.ToString() == cmbSourceDrive.SelectedItem.ToString())
            //{
            //    MessageBox.Show("请选择不同的光驱。", BaseForm.MessageBoxCaption);
            //    return;
            //}
            List<DiscFile> mediaPackFileList = GetMediaPackFiles();
            //if (mediaPackFileList != null && mediaPackFileList.Count > 1)
            //{
            //    string driveName = cmbSourceDrive.SelectedItem.ToString().Substring(0, 1);
            //    System.IO.DriveInfo mediaDrive = new System.IO.DriveInfo(driveName);
            //    if (mediaDrive.VolumeLabel != this.discBarcode)
            //    {
            //        MessageBox.Show("请放入正确的盘片", BaseForm.MessageBoxCaption);
            //        return;
            //    }
            //    mediaPackFileList.ForEach(mediaFile =>
            //    {
            //        if (File.Exists(Path.Combine(driveName + ":", mediaFile.Path)) == false)
            //        {
            //            MessageBox.Show("文件不存在该光盘上。", BaseForm.MessageBoxCaption);
            //            return;
            //        }
            //    }
            //    );
            //    pnlProcess.Visible = true;
            //}
            if (txtSavePath.Text.Trim() == "" || txtSource.Text.Trim() == "")
            {
                MessageBox.Show("请选择源文件或者目标文件。");
                return;
            }
            pnlProcess.Visible = true;
            AddWaterMark(Convert.ToInt32((cboWaterMarker.SelectedItem as KeyValue).Value) * 25, 5, txtSource.Text.Trim(), txtSavePath.Text.Trim());
            timer1.Start();

        }

        private void btnControl_MouseMove(object sender, MouseEventArgs e)
        {
            Button btn = sender as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnBurning":
                        btnBurning.BackgroundImage = global::MediaClient.Properties.Resources.发行_small1;
                        break;
                    case "btnSource":
                        btnSource.Image = global::MediaClient.Properties.Resources.浏览_1;
                        break;
                    case "btnBrowse":
                        btnBrowse.Image = global::MediaClient.Properties.Resources.浏览_1;
                        break;
                }
            }
        }

        private void btnControl_MouseLeave(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnBurning":
                        btnBurning.BackgroundImage = global::MediaClient.Properties.Resources.发行_samll;
                        break;
                    case "btnSource":
                        btnSource.Image = global::MediaClient.Properties.Resources.浏览;
                        break;
                    case "btnBrowse":
                        btnBrowse.Image = global::MediaClient.Properties.Resources.浏览;
                        break;
                }
            }
            
        }

        AddWaterMarkHelper addWaterMark = new AddWaterMarkHelper();

        /// <summary>
        /// 添加水印
        /// </summary>
        /// <param name="inivalnum">水印间隔（单位是帧）</param>
        /// <param name="strengNum">添加水印的强度</param>
        private void AddWaterMark(int inivalnum,int strengNum,string sFile,string tFile)
        {
           
            if (addWaterMark != null)
            {
                addWaterMark.InitialFlexWaterMark(sFile, tFile);
                Thread.Sleep(500);
                addWaterMark.SetWaterMarkParams(inivalnum, strengNum);
                Thread.Sleep(200);
                addWaterMark.StartFlexAddWaterMark();
            }
        }

        private void btnSource_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.RestoreDirectory = true;
            file.Filter = "MPEG FILL(*.mpg)|*.mpg";
            if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtSource.Text = file.FileName;
                
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int num = Convert.ToInt32(addWaterMark.GetProcess() * 100);
            pbProcess.Value = num;
            lblProcess.Text = pbProcess.Value.ToString() + "%";
            if (num >= 100)
            {
                timer1.Stop();
            }
        }
    }
}
